(function(Money) {
	//money动态对象
	var _moneyOjb;
	var config = {
			//小数位数
			decimalLen:Ccay.Config.Format.decimalfraction,
			//整数位最大长度
			maxLen:15,
			//是否可为负数
			negative:true,
			//数值靠左还是靠右
			align:"right",
			//币种
			currencyCode:"CNY",
			//汇率转换日期是否默认填入当前系统时间
			isCurrentDate:true,
			//设定是否只读
			readOnly:{
//				amount:false,
//				date:false,
//				code:false
			}
	}
	//组件模板,包含金额，汇率转换日期，和币种三个隐藏元素
	var templStr = ["<a class='ccay-money-btn'></a>",
				    "<input name='${currencyCodeName}' type='hidden'/>",
				    "<input name='${exchangeDateName}' type='hidden'/>",
				    "<input name='${amountName}' type='hidden'/>"].join("");

	 var factory = {
			initOp:function(money,op){
				//设置小数位
				op.decimalLen = money.dom.attr("decimalLen") || op.decimalLen;
				//设置整数位
				op.maxLen = money.dom.attr("maxLen") || op.maxLen;
				//设置数值靠左还是靠右
				op.align = money.dom.attr("align") || op.align;
				config.align != op.align && money.dom.css("text-align",op.align);
				//设置币种
				op.currencyCode = money.dom.attr("currencyCode") || op.currencyCode;
				//是否可包含负数
				money.dom.attr("negative") == "false" && (op.negative = false);
				//是否可默认使用系统日期
				money.dom.attr("isCurrentDate") == "false" && (op.isCurrentDate = false);
				//设置日期
				op.exchangeDate = op.isCurrentDate?Ccay.Core.getServerTime():"";
				
				op.currencyCodeName = money.dom.attr("currencyCodeName") || op.currencyCodeName;
				op.exchangeDateName = money.dom.attr("exchangeDateName") || op.exchangeDateName;
				op.amountName = money.dom.attr("amountName") || op.amountName;
			},
			//结构构造
			build:function(money,op){
				money.dom.after(Ccay.UI.template(templStr,op));
			},
			//事件绑定
			bindEvent:function(money, op){
				//绑定焦点事件
				money.dom.focus(function(e){
					var val = helper.amountFormat(Ccay.DataHelper.getObj(op.amountName,money.getValue()),op.decimalLen);
					$(this).val(val);
					//设置光标焦点，在ie中光标会跳到首位去
					val.length &&　Ccay.UI.setInputFocus($(this),val.length);
				}).blur(function(e){
					money.setValue($(this).val());//失去焦点后设置值
				}).next().click(function(e){
					helper.showPopup(money);
				});
				helper.keyup(money.dom,op);
				helper.keypress(money.dom,op);
			}
	}
	var helper = {
			setPopupData:function(popup,values){//从隐藏字段中获取value,设置到弹出层的文本框中显示
				popup.setValue({popupCurrencyCode:values.codeValue,popupExchangeDate:values.dateValue,popupAmount:helper.amountFormat(values.amountValue,_moneyOjb.op.decimalLen)});
				_moneyOjb.op.readOnly.code?popup.dom.find("#popupCurrencyCode").manager().disabled(false):popup.dom.find("#popupCurrencyCode").manager().disabled(true);
				_moneyOjb.op.readOnly.date?popup.dom.find("#popupExchangeDate").attr("disabled","disabled"):popup.dom.find("#popupExchangeDate").removeAttr("disabled");
				_moneyOjb.op.readOnly.amount?popup.dom.find("#popupAmount").attr("disabled","disabled"):popup.dom.find("#popupAmount").removeAttr("disabled");
			},
			getPopupData:function(values){//从弹出层中获取的文本框的值,设置到隐藏字段中
				_moneyOjb.setValue(values.popupAmount,values.popupCurrencyCode,values.popupExchangeDate)
			},
			amountFormat:function(amount,decimalLen){//金额格式化
				if(!amount){return "";}
				var amounts = amount.split(".");
				if(amounts[1] && (amounts[1].length > decimalLen)){
					//小数位超出后不对其四舍五入，截取即可
					amounts[1] = amounts[1].substring(0,decimalLen);
					amount = amounts.join(".");
				}
				amount = Ccay.Format.toNumber(amount);
				return Ccay.Format.toCurrency(isNaN(amount)?0:amount,decimalLen);
			},
			getSelectText:function(element) {//获取选中文本的长度
				 if (document.selection) { //for IE
					 return document.selection.createRange().text.length;
				 } else if (element.selectionStart || element.selectionStart === 0) {
					 return  element.selectionEnd - element.selectionStart;
				 }
				 return 0;
			},
			getPopup : function(){
				//只加载一次
				var popup = $("#ccay-money-popup").manager();
				if(popup.dom){
					return popup;
				}
				var moneyModel =Ccay.Modal.create ({
					modalName: "moneyModel",
					fields: [{field: "popupCurrencyCode",editorOp:{id:"popupCurrencyCode"}, name:$i18n("ccay.common.money.currencyCode"), type:"enum",format:{valueField:"currencyCode",displayField:"currencyCode", service:"REST:servlet/proxy/params/eFinance"}},
					         {field: "popupExchangeDate",editorOp:{id:"popupExchangeDate"}, name:$i18n("ccay.common.money.exchangeDate"), type:"date"},
					         {field: "popupAmount",editorOp:{id:"popupAmount"}, name:$i18n("ccay.common.money.amount")}]
				});
				var xFormOption = {
						modal: moneyModel,
						showHead:false,
						renderType: "edit",
						buttons:[{type:"imgBtn",icon:"yes",text:"ccay.common.button.ok",attr:{eno:"ok"}},
						         {type:"imgBtn",icon:"reset",text:"ccay.common.label.reset",attr:{eno:"reset"}}],
						operation:{
							ok:function(e,form){
								//验证数据
								if(!form.valid()){return;}
								//获取弹出框中的数据，设置到隐藏字段中
								helper.getPopupData(form.getValue());
								_moneyOjb.dom.focus();
								//money对象置空
								_moneyOjb = null;
								//隐藏弹出框
								form.hide();
							},
							reset:function(e,form){
								helper.setPopupData(form,_moneyOjb.dom.data("values"));
								form.dom.find(".error-ctr").removeClass("error error-ctr").next("label.error").hide();
							}
						}
					};
				popup = $.create("div",null,"ccay-money-popup").attr("tabIndex","-1").appendTo(Ccay.UI.getPopupPanel()).xForm(xFormOption);
				//设置弹出层的focusout事件
				popup.dom.focusout(function(e){
					var poper = $(this);
					var isPopup= true;
					poper.focusin(function(ev){
						isPopup = false;
					});
					setTimeout(function(){
						if(isPopup){
							var isVisiable = $($("#popupCurrencyCode").data("selector")).isVisiable() || $("#popupExchangeDate").manager("XCalendar").isPopup();
							if(!isVisiable && poper.isVisiable()){
								if(!popup.valid()){return;}
								helper.getPopupData(popup.getValue());
								_moneyOjb = null;
								popup.hide();
							}
						}
					},10);
				}).click(function(e){
					e.stopPropagation();
				});
				Ccay.UI.delayEvent2($("#popupAmount"),'keyup',function(){
					_moneyOjb && $(this).val(helper.amountFormat($(this).val(),_moneyOjb.op.decimalLen));
				});
				this.keypress($("#popupAmount"),_moneyOjb.op);
				return popup;
		    },
		    showPopup : function(money){
		    	_moneyOjb = money;
				var popuper = this.getPopup(), input = _moneyOjb.dom;
				Ccay.UI.popup( input, popuper.dom, {top: input.height() + 4 }, true, true, null, true);
				!_moneyOjb.dom.data("values") && _moneyOjb.setValue("");
				this.setPopupData(popuper,_moneyOjb.dom.data("values"));
				popuper.dom.focus();
			},
			keyup : function(element,op){
			    	//keyup事件延迟
					/*Ccay.UI.delayEvent2(element,'keyup',function(){
						if(this[0] == document.activeElement){
							$(this).val(helper.amountFormat($(this).val(),op.decimalLen));
						}
					});*/
			},
			keypress : function(element,op){
			    	//设置键盘事件
					element.keypress(function(e){
						var value = $(element).val(),code = e.keyCode,ignore =[44];//44逗号
					     if(op.negative){//添加负号
					    	 ignore.push(45);
					     }
					     var decimalPostion = value.indexOf(".");
					     if(decimalPostion == -1){//小数点
					    	 ignore.push(46);
					     }
					     if(code == 13 || code == 108){
				         	$(this).val(helper.amountFormat($(this).val(),op.decimalLen));
				         	return ;
				         }
					     
					     //输入是否在范围内
					     if((code<48 || code>57) && $.inArray(code,ignore)==-1){
					    	 e.preventDefault();
					         return;
					     }
					     //光标选中的字符
				         var selectText = helper.getSelectText(element);
				         //光标位置
				         var cursorPosition =Ccay.UI.getInputFocus(element);
				         //判断负数输入
				         if(code == 45 && (cursorPosition != 0 || /\-/.test(value)) && !selectText){
				        	 e.preventDefault();
				        	 return;
				         }
				         
				         var integer = value.replace(/[,-]/g,"");//整数部分,剔除逗号或负号
				         if(decimalPostion != -1){
				        	 integer = integer.substr(0,integer.indexOf(".")); //有小数点就截取整数
				         }
				         // 当为最大整数位的时候 选中字符可以进行修改
						 if(integer.length >= op.maxLen && !selectText){
							 //如果没有选中字符，则判断是否输入小数点、或小数点以后的数字
							 //小数点位置
							 //如果存在小数点并且在小数前前输入则不通过
							 if(decimalPostion != -1 && decimalPostion+1 > cursorPosition && code != 45){
								 e.preventDefault();
					        	 return;
							 }
							 //如果不存在小数点并且输入的字符不为‘.’和‘-’则不通过
							 if(decimalPostion == -1 && $.inArray(code,[45,46])==-1){
								 e.preventDefault();
					        	 return;
							 }
				     	 }
					});
			}
	 }
	var flow = {
		init: function (money, op) {
			factory.initOp(money, op);
		},
		build: function (money, op) {
			factory.build(money, op);
		},
		bindEvent: function (money, op) {
			factory.bindEvent(money, op);
		}
	};
	
	var manager = {
			setValue : function(amountValue,codeValue,dateValue) {
				var values = this.dom.data("values")||{};
				amountValue = (amountValue && amountValue.replace(/,/g,"")) || "";
				codeValue = codeValue || values.codeValue || this.op.currencyCode;
				dateValue = dateValue || values.dateValue || this.op.exchangeDate;
				//重新设置money的data对象值
				this.dom.data("values",{amountValue:amountValue,codeValue:codeValue,dateValue:dateValue});
				//设置隐藏属性值
				this.findByName(this.op.amountName).val(values.amountValue);
				this.findByName(this.op.currencyCodeName).val(values.codeValue);
				this.findByName(this.op.exchangeDateName).val(values.dateValue);
				//设置显示值
				var showText = helper.amountFormat(amountValue,this.op.decimalLen);
				if( showText!=="" && this.dom[0] != document.activeElement){
					showText =  codeValue + showText;
				}
				this.dom.ccaySetValue(showText);
				this.op.callback && this.op.callback.call(this,this.getValue());
			},
			getValue:function(){
				var values = this.dom.data("values")||{},resultData={};
				Ccay.DataHelper.setObj(this.op.amountName,resultData, values.amountValue);
				Ccay.DataHelper.setObj(this.op.currencyCodeName,resultData, values.codeValue);
				Ccay.DataHelper.setObj(this.op.exchangeDateName,resultData, values.dateValue);
				return resultData;
			},
			setReadOnly:function(readOnly){
				$.extend(this.op.readOnly,readOnly);
			},
			findByName:function(name){
				return this.dom.siblings('[name="'+ name + '"]');
			}
	}
	var XMoney = Ccay.UI.XControl("XMoney", flow, config, manager);
	$.fn.ccayMoney = function(op){
		return this.each( function(){
	 		var input = $( this );
	 		if(!input.attr("init")){
	 			input.attr("init", true);
	 			new XMoney( input , op );
	 		}
	 	} );
	}
	
	//将接口添加到自动UI初始化集合中，加载页面ccayLoad 都会自动调用该处理器初始化UI
	Ccay.UI.Renders.add(function(initCtrs, contenxt){
		initCtrs.filter(".ccay-money").ccayMoney();
	});
})(Ccay.UI.XMoney);